#include "bsp_delay_us.h"

#include "stm32f4xx_hal.h"

void delay_us(uint16_t us)
{
	assert_param(us <= 1000);

	uint32_t target_cnt = us * (SystemCoreClock / 1000000);
	uint32_t reload_cnt = SysTick->LOAD;
	uint32_t elapse_cnt = 0;

	uint32_t current_cnt;
	uint32_t previous_cnt = SysTick->VAL;
	while (1)
	{
		current_cnt = SysTick->VAL;

		if (current_cnt <= previous_cnt)
		{
			elapse_cnt += previous_cnt - current_cnt;
		}
		else
		{
			elapse_cnt += previous_cnt + reload_cnt - current_cnt;
		}

		previous_cnt = current_cnt;

		if (elapse_cnt >= target_cnt)
		{
			break;
		}
	}
}